package com.yqg.protection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yqg.protection.entity.RoleMenu;
import com.yqg.protection.mapper.RoleMenuMapper;
import com.yqg.protection.service.IMenuService;
import com.yqg.protection.service.IRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * RoleMenuServiceImpl 服务实现类
 * @author suzhuang
 * @since 2023-07-05
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private IMenuService menuService;


    public List<Integer> getByRoleId(Long roleId) {
        return roleMenuMapper.getByRoleId(roleId);
    }


    public static List<Integer> getKeysFromMap(Map<Integer, Integer> map, List<Long> list) {
        List<Integer> keys = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (list.contains(Long.valueOf(entry.getValue()))) {
                keys.add(entry.getKey());
            }
        }
        return keys;
    }

    @Override
    public Boolean updateRoleMenu(List<Long> checkedId) {
        //先删除原数据表中与该role_id相同的menu_id
        Long roleId = checkedId.get(checkedId.size() - 1);
        deleteByRoleId(roleId);
        checkedId.remove(checkedId.size() - 1);

        ArrayList<RoleMenu> roleMenus = new ArrayList<>();

        for (int i = 0; i < checkedId.size(); i++) {
            //向数据库中存
            RoleMenu roleMenu = new RoleMenu();
            //设置role_id
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(Long.valueOf(checkedId.get(i)));
            roleMenus.add(roleMenu);
        }
        return saveBatch(roleMenus);
    }

    /**
     * 通过roleId删除
     */
    public void deleteByRoleId(@PathVariable Long roleId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("role_id", roleId);
        remove(qw);
    }
}
